#include<iostream>
using namespace std;
#include"tcpServer.hpp"
#include<memory>
#include<string.h>

using namespace Server;


void my_err(char* message){
    printf("%s使用错误，应该加上端口\n",message);
}

string my_toupper(const string& s2){
    string tmp;
    for(auto e: s2){
        tmp+=toupper(e);
    }
    return tmp;
}
void serviceio(int sock){
    //先读取客户端发过来的数据
    while(1){
        char buffer[1024];
        int n = read(sock,buffer,sizeof(buffer-1));
        if(n > 0){
            buffer[n] =0;
            cout<<buffer<<endl;


            //业务逻辑执行后再把数据返回给客户端
            string outbuffer;
            outbuffer = buffer;
            string outbuffer2 = my_toupper(outbuffer);


            outbuffer2+="[server echo]";
            // int ret = sizeof(buffer);
            // int i = 0;
            // while(i < ret){
            //     outbuffer += toupper(buffer[ret]);
            //     i++;
            // }
            

            //发回给客户端
            write(sock,outbuffer2.c_str(),outbuffer2.size());
        }else if(n == 0){
            printf("客户端断开了连接。。\n");
        }else{
            break;
        }
    }
}

int main(int argc,char* argv[]){
    if(argc != 2){
        my_err(argv[0]);
        exit(1);
    }

    uint16_t port  = atoi(argv[1]);

    unique_ptr<tcpServer> ret(new tcpServer(serviceio,port));
    ret->initServer();
    ret->start();







    return 0;
}